package model

import (
	"fmt"
	"context"
	"ginblog/utils"
	"ginblog/utils/errmsg"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
	"mime/multipart"
	"io"	
	"os"
	"time"
	"path/filepath"
	"strconv"
)

var AccessKey = utils.AccessKey
var SecretKey = utils.SecretKey
var Bucket = utils.Bucket
var ImgUrl = utils.QiniuSever

var UploadDrive = utils.UploadDrive

func UpLoadFile(file multipart.File, fileSize int64,fileHeader *multipart.FileHeader) (string, int) {

	
if UploadDrive=="host" {
	// file, handler, err := c.Request.FormFile("file")
	// if err != nil {
	// 	return "", errmsg.ERROR
	// }
	timenow := time.Now().Unix()
	fin := filepath.Ext(fileHeader.Filename)
	out, err := os.Create("public/uploads/" +strconv.FormatInt(timenow, 10)+fin )
	if err != nil {
		return "", errmsg.ERROR
	}
	io.Copy(out, file)

	url:="/uploads/" +strconv.FormatInt(timenow, 10)+fin
	return url, errmsg.SUCCSE
	
	
// 	timenow := time.Now().Unix()
// 	ext,_:=GetImgExt(file)
	
// 	// filebuf := make([]byte,fileSize)
// 	// _, err = file.Read(filebuf)


// 	path, err := os.Executable()
// if err != nil {
	
// }
// dir := path.Dir(path)
// upload_path:=path.Join(dir, "/public/uploads/")

// 	file, err := os.Create(upload_path)


// out, _ = os.OpenFile(upload_path+strconv.FormatInt(timenow, 10)+ext, os.O_RDWR, 0666)

// 	io.Copy(out, file)

// 	// defer file.Close()

// 	// file.Write(fileBuffer)

// 	return url, errmsg.SUCCSE
}

if  UploadDrive=="qiniu" {

	putPolicy := storage.PutPolicy{
		Scope: Bucket,
	}
	mac := qbox.NewMac(AccessKey, SecretKey)
	upToken := putPolicy.UploadToken(mac)
	fmt.Println(upToken)

	cfg := storage.Config{
		Zone:          &storage.ZoneHuadong,
		UseCdnDomains: false,
		UseHTTPS:      false,
	}

	putExtra := storage.PutExtra{}

	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}

	err := formUploader.PutWithoutKey(context.Background(), &ret, upToken, file, fileSize, &putExtra)
	if err != nil {
		fmt.Println(err.Error())
		return "", errmsg.ERROR
	}
	url := ImgUrl + ret.Key
	return url, errmsg.SUCCSE
}
	
return "", errmsg.ERROR

}